<?php
declare (strict_types = 1);

namespace app\api\controller;

use Ali\OSS\OSS;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\facade\Cache;
use think\facade\Db;
use think\Request;
use think\Response;

class Exam
{
    const TABLE_NAME = 'answer';
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index(Request $request)
    {
        //
        //
        $params = $request->get();
        $page = (int)$params['pageNum'];
        $pageSize = (int)$params['pageSize'];
        $cache = $request->cache;
        $condition = array();
       if(isset($params['active'])&&!empty($params['active'])){
           $condition[]=['active_id','=',$params['active']];
       }else{
           return error([],9004,'请选择考试场次');
       }
        if (isset($params['keywords']) && !empty($params['keywords'])) {
            $condition[] = ['baseinfo.name', 'like', '%' . $params['keywords'] . '%'];
        }
       if (isset($params['status'])) {
            $condition[] = ['answer.status', '=', $params['status']];
        }
        $field = ["answer.id,answer.level,answer.video_url,active.type,answer.video_local_url,answer.status,answer.video_status,baseinfo.name,baseinfo.contact_person,baseinfo.phone", Db::raw("FROM_UNIXTIME(answer.create_time, '%Y-%m-%d %H:%i:%s') AS createTime")];
        try {
            $paginate =  Db::name(self::TABLE_NAME)->alias('answer')->
            leftJoin('examinee_baseinfo baseinfo','answer.examinee_id=baseinfo.id')
                ->leftJoin('active','active.id=answer.active_id')
                ->where($condition)->field($field)->paginate(['page' => $page, 'list_rows' => $pageSize]);
            return success([
                'total' => $paginate->total(),
                'list' => $paginate->items(),
                'current_page' => $paginate->currentPage(),
                'last_page' => $paginate->lastPage(),
                'debug'=>Db::getLastSql()
            ]);
        } catch (DbException $e) {
            return error([], 9002, $e->getMessage());
        }
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
        $data = Db::name(self::TABLE_NAME)->alias('answer')
            ->leftJoin('examinee_baseinfo baseinfo','baseinfo.id=answer.examinee_id')
            ->field(['baseinfo.*','answer.level'])
            ->find($id);
       return success($data);
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }
    public function upload(Request $request){

        try {
            $cache = $request->cache;
            $file = $request->file('file');
            if ($file) {
                
                if($file->getSize()>500*1024*1024){
                    throw new Exception('视频大小超过了500M');
                }
                $details = Db::name('answer')->where('id','=',$request->post('answer'))->find();
                $examinee  =Db::name('examinee_baseinfo')->where(['id'=>$details['examinee_id']])->find();
                $active =Db::name('active')->where('id','=',$details['active_id'])->find();
                if(strtotime($active['apply_end'])<time()){
                    throw new Exception('报名已截止，无法上传视频',9001);
                }
                $uploadPath = root_path() . 'public/uploads/video/'.$details['active_id'].'/';
                if (!is_dir($uploadPath)) {
                    mkdir($uploadPath, 0777, true);
                }
                // 判断是否已经把视频上传到oss  如果已经上传了就调用接口删除掉
                if($details['video_status']==2 && !empty($details['video_url'])){
                    $oss= new Oss();
                    $oss->deleteFile($details['video_url']);
                }
                $fileName=$file->getOriginalName();
                $ext = '.'.pathinfo($fileName, PATHINFO_EXTENSION);
                $saveName = $examinee['name'].'_'.($details['type']==1?'朗诵':'主持').'_'.$details['level'].'级考试视频'.$ext;
                // 把上传的视频按照指定格式移动到指定位置
                $info=$file->move($uploadPath, $saveName);
                //  移动成功后将数据保存到数据库
                $updateData = [
                    'id' => $details['id'],
                    'video_url'=>null,
                    'video_local_url' => 'uploads/video/'.$details['active_id'].'/'.$saveName,
                    'video_status' => 1,
                    'create_time' => time(),
                    'status' => 2
                ];
                $update = Db::name('answer')->update($updateData);
                if (!$update) {
                    throw new Exception('上传视频失败', 9007);
                }
                return success();
            } else {
                throw new Exception('视频上传失败', 9003);
            }
        } catch (\Exception $e) {
            writeLogToDb('上传视频失败',$cache['id'],0,['msg'=>$e->getMessage(),'code'=>$e->getCode()]);
            return error([], $e->getCode() ?: 9006, $e->getMessage());
        }
    }

    /** 根据id获取本厂考试提交的视频
     * @param $id
     * @return Response
     */
    public function getVideo($id):Response{
        try{
            $data = Db::name(self::TABLE_NAME)->find($id);
            return success($data);
        }catch(\Exception $e){
            return error([],$e->getCode()?:9006,$e->getMessage());
        }

    }
}
